{% extends "base.html" %}

{% block content %}
<div class="page-title">
    <h3>在下方输入要修改的采购清单号：</h3>
</div>
<div class="form-container">
    <form id="modify-purchase-form">
        <label for="id">采购清单号（此项仅作查找之用，若想修改本项请在下方进行）：</label>
        <input type="number" id="id" name="id" class="input-field" required><br>
        <button type="button" class="login-button" id="search-button">查找</button>
        <div id="modify-fields" style="display:none;">
            <label for="employee_id">员工编号：</label>
            <input type="number" id="employee_id" name="employee_id" class="input-field" required><br>
            <label for="quantity">采购数量：</label>
            <input type="number" id="quantity" name="quantity" class="input-field" required><br>
            <label for="total_price">采购总价：</label>
            <input type="number" id="total_price" name="total_price" class="input-field" required><br>
            <label for="purchase_time">采购时间：</label>
            <input type="datetime-local" id="purchase_time" name="purchase_time" class="input-field" required><br>
            <label for="remark">备注：</label>
            <textarea id="remark" name="remark" class="input-field"></textarea><br>
            <label for="new_id">新的采购清单号（如不修改请留空）：</label>
            <input type="number" id="new_id" name="new_id" class="input-field"><br>
            <div class="button-container">
                <button type="submit" class="login-button">保存</button>
                <button type="reset" class="login-button" style="background-color: grey;">重置</button>
            </div>
        </div>
    </form>
</div>

<script>
    document.getElementById('search-button').addEventListener('click', function() {
        var id = document.getElementById('id').value;
        if (id) {
            fetch(`/api/purchases/${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert('该采购清单号不存在');
                        document.getElementById('modify-fields').style.display = 'none';
                    } else {
                        document.getElementById('employee_id').value = data['员工编号'];
                        document.getElementById('quantity').value = data['采购数量'];
                        document.getElementById('total_price').value = data['采购总价'];
                        document.getElementById('purchase_time').value = new Date(data['采购时间']).toISOString().slice(0, 16);
                        document.getElementById('remark').value = data['备注'];
                        document.getElementById('modify-fields').style.display = 'block';
                    }
                }).catch(error => {
                    console.error('Error:', error);
                    alert('查找采购清单失败');
                });
        } else {
            alert('请输入采购清单号');
            document.getElementById('modify-fields').style.display = 'none';
        }
    });

    document.getElementById('modify-purchase-form').addEventListener('submit', function(event) {
        event.preventDefault();

        var id = document.getElementById('id').value;
        var newId = document.getElementById('new_id').value;
        const formData = new FormData(this);
        const data = Object.fromEntries(formData.entries());

        if (newId && newId !== id) {
            if (!confirm('此次修改涉及采购清单号，是否确认修改？')) {
                return;
            }
            data.new_id = newId;
        }

        fetch(`/api/purchases/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(response => {
            if (response.ok) {
                alert('采购清单修改成功');
                this.reset();
                document.getElementById('modify-fields').style.display = 'none';
            } else {
                response.json().then(data => {
                    if (response.status === 409) {
                        alert('修改采购清单失败: ' + data.error);
                    } else {
                        alert('修改采购清单失败: ' + data.error);
                    }
                });
            }
        }).catch(error => {
            console.error('Error:', error);
            alert('修改采购清单失败');
        });
    });

    document.querySelector('button[type="reset"]').addEventListener('click', function(event) {
        if (!confirm('是否确定重置已输入信息？')) {
            event.preventDefault();
        }
    });
</script>
{% endblock %}
